package com.xzl.xep.web.controller;



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.xzl.xep.exception.FormValidationException;
import com.xzl.xep.pojo.Operator;
import com.xzl.xep.service.OperatorService;
import com.xzl.xep.web.interseptor.WebConstants;


@Controller
public class LoginController extends BaseController {

	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	
	@Autowired
	private OperatorService operatorService;
	
	
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
 	public String login2(){
 		return "login";  

	}
	
	@RequestMapping(value = "/logout")
	public String logout(){
		session.removeAttribute(WebConstants.SESSION_OPERATOR);
	
		this.setCookieInSession(WebConstants.COOKIE_OPERATOR_ID, null);
		this.saveCookie();
		
		return 	"redirect:/";
	}
	
	
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam String account, @RequestParam String password, Model model) {
		
		FormValidationException validate = new FormValidationException();
		validate.toView("login");
	    validate.addFiled("account", account==null?"":account);
	    validate.addFiled("password", password==null?"":password);
	    
	    String ip;
	    
		 if (request.getHeader("x-forwarded-for") == null) {
			ip= request.getRemoteAddr();
		 }else{
			ip = request.getHeader("x-forwarded-for");
		 }
		
		logger.debug("用户"+account+"尝试登录，ip:"+ip) ;
		 
		if (StringUtils.isBlank(account)) {
			validate.addError("account", "", "账户不能为空！");
		
		}
		if (StringUtils.isBlank(password)) {
			validate.addError("password","", "密码不能为空！");
		}
		
		if(validate.hasError()) throw validate;
		
		Operator op = operatorService.getOperatorByAccount(account);
		
		if(op == null){
			validate.addError("account", account,"账户信息不存在！");
			logger.debug("登录账户不存在！");
			throw validate;
		}
		
		if(!op.matchPassword(password)){
			validate.addError("password", password, "密码错误！");
			logger.debug("登录账户密码错误！");
			throw validate;
		}
	
		op.setLastLoginIp(ip);
		
		operatorService.login(op);
		
		this.session.setAttribute(WebConstants.SESSION_OPERATOR, op);
		
		this.setCookieInSession(WebConstants.COOKIE_OPERATOR_ID, op.getId());
		this.saveCookie();
		
		return 	"redirect:/";
		
	}
}
